package com.ms.services.mail;

import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Properties;

/**
 * Created by RAZANERO on 11/03/14.
 */
public class MailUtil {

    public static void send(MailAuthBean mailAuthBean, String subject, String htmlContent) throws MessagingException {
        send(mailAuthBean, subject, htmlContent, null);
    }

    public static void send(MailAuthBean mailAuthBean, String subject, String htmlContent, List<File> fileList) throws MessagingException {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(mailAuthBean.getHost());
        javaMailSender.setPort(25);
        javaMailSender.setUsername(mailAuthBean.getUser());
        javaMailSender.setPassword(mailAuthBean.getPassword());
        Properties properties = javaMailSender.getJavaMailProperties();
        int timeout = 10000;
        properties.put("mail.smtp.connectiontimeout", timeout);
        properties.put("mail.smtp.timeout", timeout);
        javaMailSender.setJavaMailProperties(properties);

        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        message.setSubject(subject);
        message.setFrom(mailAuthBean.getFrom());
        String[] sendTo = StringUtils.split(mailAuthBean.getTo(), ";");
        message.setTo(sendTo);
        message.setText(htmlContent, true);
        if (fileList != null && fileList.size() > 0) {
            for (File file : fileList) {
                message.addAttachment(file.getName(), file);
            }
        }
        javaMailSender.send(mimeMessage);
    }
}
